package cn.tedu._05mvcboot04.controller;

import cn.tedu._05mvcboot04.commen.response.JsonResult;
import cn.tedu._05mvcboot04.commen.response.StatusCode;
import cn.tedu._05mvcboot04.mapper.UserMapper;
import cn.tedu._05mvcboot04.pojo.dto.ArticleDTO;
import cn.tedu._05mvcboot04.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot04.pojo.entity.Article;
import cn.tedu._05mvcboot04.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "用户模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录功能
     */
    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,
                            @ApiIgnore HttpSession session){
        //打桩
        log.debug(userLoginDTO.toString());
        //校验用户名和密码
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        if (userVO == null)
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        //用户登录
        session.setAttribute("user",userVO);
        return JsonResult.success();
    }

    /**
     * 发布文章功能
     */
    @ApiOperation(value = "发布文章")
    @PostMapping(value = "/article")
    public JsonResult insertArticle(@RequestBody @Validated ArticleDTO articleDTO,
                                    @ApiIgnore HttpSession session){
        //打桩
        log.debug(articleDTO.toString());
        //校验登录状态交给拦截器
        //发布文章
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(articleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.success();
    }

    /**
     * 查看指定文章
     */
    @ApiOperation(value = "查看指定文章")
    @GetMapping(value = "/selectByArticleId")
    public JsonResult selectByArticleId(
            @RequestParam @Range(min = 1,max = 100,message = "文章编号在1-100之间") Integer id){
        return JsonResult.success(userMapper.selectByArticleId(id));
    }
}
